#include "HttpServer.hpp"
#include <memory>

void Usage(std::string proc)
{
    std::cout << "\nUsage:\n" << proc << "\tport" << std::endl;
}

bool Get(const request& req, response* resp)
{
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "version: " << req.version << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    std::cout << req.inbuffer << std::endl;

    std::string respline = "GET 200 OK\r\n";
    // std::string respheader = "Content-Type: ";
    std::string respheader;
    Util::ToSuffix(req.suffix, &respheader);
    respheader += std::to_string(req.size);
    std::string respblank = "\r\n";
    std::string body;
    if(!Util::readFile(req.path, &body))
    {
        Util::readFile("./wwwroot/404.html", &body);
    }
    resp->outbuffer += respline;
    resp->outbuffer += respheader;
    resp->outbuffer += respblank;
    resp->outbuffer += body;
    return true;
}   

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        Usage(argv[0]);
    }

    uint16_t port = atoi(argv[1]);
    std::unique_ptr<tcps::HttpServer> htpsvr(new tcps::HttpServer(port, Get));
    htpsvr->initHttpServer();
    htpsvr->runHttpServer();

    return 0;
}